Repository navigation
feat: test infrastructure consolidation — base classes, auth/response helpers, factory hooks (PR#1) - #70
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors and centralizes integration testing infrastructure by introducing new base classes like IntegrationTestBase and IntegrationCollectionTestBase, a centralized TestAppDbContextFactory for Postgres tests, and several helper extensions for HttpClient and HttpResponseMessage. The feedback suggests improving consistency between the base classes by centralizing traits and service helper methods, disabling automatic redirects for the default test client, and enhancing error reporting during JSON deserialization by including the raw response body in exceptions.
| using Microsoft.AspNetCore.Mvc.Testing; | ||
| using Xunit; | ||
|
|
||
| namespace APITemplate.Tests.Integration; | ||
|
|
||
| public abstract class IntegrationCollectionTestBase | ||
| { | ||
| protected CustomWebApplicationFactory Factory { get; } | ||
| protected HttpClient Client => | ||
| field ??= Factory.CreateClient( | ||
| new WebApplicationFactoryClientOptions { AllowAutoRedirect = false } | ||
| ); | ||
| protected static CancellationToken Ct => TestContext.Current.CancellationToken; | ||
|
|
||
| protected IntegrationCollectionTestBase(CustomWebApplicationFactory factory) => | ||
| Factory = factory; | ||
| } |
There was a problem hiding this comment.
To fulfill the goal of centralizing integration test traits as mentioned in the PR description, and to provide the same utility methods as IntegrationTestBase, this class should include the category traits and the service helper methods (GetService and CreateScope).
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace APITemplate.Tests.Integration;
[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public abstract class IntegrationCollectionTestBase
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client =>
field ??= Factory.CreateClient(
new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }
);
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
protected IntegrationCollectionTestBase(CustomWebApplicationFactory factory) =>
Factory = factory;
protected T GetService<T>()
where T : notnull => Factory.Services.GetRequiredService<T>();
protected IServiceScope CreateScope() => Factory.Services.CreateScope();
}| using Microsoft.Extensions.DependencyInjection; | ||
| using Xunit; | ||
|
|
||
| namespace APITemplate.Tests.Integration; | ||
|
|
||
| [Trait("Category", "Integration")] | ||
| [Trait("Docker", "true")] | ||
| public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory> | ||
| { | ||
| protected CustomWebApplicationFactory Factory { get; } | ||
| protected HttpClient Client => field ??= Factory.CreateClient(); |
There was a problem hiding this comment.
For consistency with IntegrationCollectionTestBase and to better support API testing (where inspecting redirect responses is often necessary), consider disabling automatic redirects for the default Client.
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace APITemplate.Tests.Integration;
[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory>
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client => field ??= Factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
| var body = await response.Content.ReadAsStringAsync(ct); | ||
| return JsonSerializer.Deserialize<T>(body, TestJsonOptions.CaseInsensitive) | ||
| ?? throw new InvalidOperationException( | ||
| $"Response body could not be deserialized to {typeof(T).Name}. Raw: {body}" | ||
| ); |
There was a problem hiding this comment.
When deserialization fails (e.g., due to invalid JSON), the resulting JsonException does not typically include the response body. Wrapping this in a try-catch to provide the raw body in the exception message significantly improves the debugging experience for failed integration tests.
var body = await response.Content.ReadAsStringAsync(ct);
try
{
return JsonSerializer.Deserialize<T>(body, TestJsonOptions.CaseInsensitive)
?? throw new InvalidOperationException($"Response body is null. Raw: {body}");
}
catch (JsonException ex)
{
throw new InvalidOperationException($"Response body could not be deserialized to {typeof(T).Name}. Raw: {body}", ex);
}There was a problem hiding this comment.
Pull request overview
Consolidates integration/smoke test infrastructure in APITemplate.Tests by introducing shared base classes and helper extensions, and by adding lightweight configuration hooks to the test WebApplicationFactory, with some Postgres test setup extraction.
Changes:
- Added
IntegrationTestBase/IntegrationCollectionTestBaseplus auth/response helper extensions to reduce boilerplate across integration tests. - Added
CustomWebApplicationFactoryhooks (AdditionalConfiguration,AdditionalServiceConfiguration) to support test-specific overrides without fullConfigureWebHostoverrides. - Extracted Postgres
AppDbContext+UnitOfWorkcreation intoTestAppDbContextFactoryand refactoredPostgresTestBase/SmokeTestBaseaccordingly.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/APITemplate.Tests/Integration/Smoke/SmokeTestBase.cs | Refactors smoke base to inherit shared collection base and reuse shared Factory/Client/Ct. |
| tests/APITemplate.Tests/Integration/Postgres/TestAppDbContextFactory.cs | New helper to create AppDbContext + UnitOfWork for Postgres tests. |
| tests/APITemplate.Tests/Integration/Postgres/PostgresTestBase.cs | Uses TestAppDbContextFactory to reduce duplication in Postgres base. |
| tests/APITemplate.Tests/Integration/IntegrationTestBase.cs | New base class for fixture-based integration tests + service helpers. |
| tests/APITemplate.Tests/Integration/IntegrationCollectionTestBase.cs | New base class for collection-fixture tests with shared Client and Ct. |
| tests/APITemplate.Tests/Integration/Helpers/HttpResponseTestExtensions.cs | Adds shared response assertions and JSON deserialization helper. |
| tests/APITemplate.Tests/Integration/Helpers/HttpClientAuthExtensions.cs | Adds fluent HttpClient auth helpers over IntegrationAuthHelper. |
| tests/APITemplate.Tests/Integration/CustomWebApplicationFactory.cs | Adds optional configuration/service hooks for extending factory behavior. |
| tests/APITemplate.Tests/APITemplate.Tests.csproj | Updates explicit compile allowlist to include new helper/base files. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| <Compile Include="Integration\IntegrationAuthHelper.cs" /> | ||
| <Compile Include="Integration\IntegrationCollectionTestBase.cs" /> | ||
| <Compile Include="Integration\IntegrationTestBase.cs" /> | ||
| <Compile Include="Integration\Postgres\BffSessionPostgresTests.cs" /> |
There was a problem hiding this comment.
Integration\**\*.cs is removed from compilation and only explicitly included files are compiled. This PR adds Integration/Postgres/TestAppDbContextFactory.cs but it is not included here, so it will be excluded and PostgresTestBase will fail to compile. Add a <Compile Include="Integration\Postgres\TestAppDbContextFactory.cs" /> entry (or switch to a glob for the Postgres folder).
| public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory> | ||
| { | ||
| protected CustomWebApplicationFactory Factory { get; } | ||
| protected HttpClient Client => field ??= Factory.CreateClient(); | ||
| protected static CancellationToken Ct => TestContext.Current.CancellationToken; | ||
|
|
||
| protected IntegrationTestBase(CustomWebApplicationFactory factory) => Factory = factory; |
There was a problem hiding this comment.
IntegrationTestBase hardcodes IClassFixture<CustomWebApplicationFactory>, which prevents using it with existing specialized factories that inherit from CustomWebApplicationFactory (e.g., EmptyRedisWebApplicationFactory, RateLimitingWebApplicationFactory). This also limits the usefulness of the new AdditionalConfiguration/AdditionalServiceConfiguration hooks for derived factories. Consider making the base generic (IntegrationTestBase<TFactory> : IClassFixture<TFactory> where TFactory : CustomWebApplicationFactory) so tests can opt into custom factories while still using the shared base behavior.
| public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory> | |
| { | |
| protected CustomWebApplicationFactory Factory { get; } | |
| protected HttpClient Client => field ??= Factory.CreateClient(); | |
| protected static CancellationToken Ct => TestContext.Current.CancellationToken; | |
| protected IntegrationTestBase(CustomWebApplicationFactory factory) => Factory = factory; | |
| public abstract class IntegrationTestBase<TFactory> : IClassFixture<TFactory> | |
| where TFactory : CustomWebApplicationFactory | |
| { | |
| protected TFactory Factory { get; } | |
| protected HttpClient Client => field ??= Factory.CreateClient(); | |
| protected static CancellationToken Ct => TestContext.Current.CancellationToken; | |
| protected IntegrationTestBase(TFactory factory) => Factory = factory; |
- IntegrationTestBase / IntegrationCollectionTestBase: abstract bases that eliminate per-class Factory/Client/Ct boilerplate and centralise [Trait] attributes - HttpClientAuthExtensions: fluent AsAdmin/AsUser/AsTenantAdmin/WithAuth/WithoutAuth wrappers over IntegrationAuthHelper - HttpResponseTestExtensions: centralised ReadJsonAsync<T> and ShouldBeStatusAsync helpers - CustomWebApplicationFactory: AdditionalServiceConfiguration / AdditionalConfiguration hooks for subclass customisation without full override - SmokeTestBase: inherits IntegrationCollectionTestBase, removes duplicated fields - TestAppDbContextFactory: extracts DbContext + UnitOfWork creation from PostgresTestBase - .csproj: opts new files into the explicit compile allowlist
…stBase Matches original SmokeTestBase.CreateClient() behaviour (default options). The option was absent before the refactor — keeping it would silently change redirect-handling for all smoke tests.
…proved JSON deserialization error handling
…ntext helpers ToProblemDetails reads RequestServices for ErrorDocumentationOptions and falls back to scheme+host for the Type URI. Tests were failing because DefaultHttpContext leaves both null by default.
Previous cleanup accidentally removed files that were already updated for the modular architecture. Re-adds them with their fixes applied and updates csproj to explicitly include the integration test files.
5cb8b88 to
f9dcea2
Compare
…antAsync helper IdentityTokenValidatedPipeline rejects tokens whose sub claim doesn't match a provisioned user in the DB. Tests were authenticating with a random sub, causing 401 on every request. Fix: RolesControllerTests now seeds an admin user via IAsyncLifetime and authenticates with that user's KeycloakUserId as the token subject. AssignUserRoles_Success seeds the target user inside the same tenant via the new SeedUserInTenantAsync helper.
Summary
Factory/Client/Ctboilerplate and centralise[Trait("Category","Integration")]+[Trait("Docker","true")]attributes; exposeGetService<T>()andCreateScope()AsAdmin(),AsUser(),AsTenantAdmin(),WithAuth(),WithoutAuth()wrappers overIntegrationAuthHelper; enable one-liner auth:_client.AsAdmin().GetAsync(url, ct)ReadJsonAsync<T>()andShouldBeStatusAsync()/ShouldBeOkAsync()to remove ~5-line parse boilerplate from each testAdditionalServiceConfigurationandAdditionalConfigurationproperties let subclasses inject config without a fullConfigureWebHostoverrideIntegrationCollectionTestBase; removes duplicated_factory,Client,CtfieldsAppDbContext+UnitOfWorkcreation fromPostgresTestBase; base shrinks from ~110 to ~60 lines.csproj— new files opted into the explicit compile allowlistNotes
This is PR #1 of 2 (infrastructure only). No existing test class is changed here — PR #2 will migrate the 24
IClassFixture<CustomWebApplicationFactory>test classes toIntegrationTestBaseand replace directIntegrationAuthHelper.Authenticatecalls with the new extension methods.Test Plan
dotnet build— 0 errors, 0 warningsdotnet test --filter "Category=Integration"— requires Docker (run in CI)dotnet test --filter "Category=Smoke"— requires Docker (run in CI)